package com.tornado.community.controller;

import com.tornado.community.advice.Constant;
import com.tornado.community.mapper.NotificationMapper;
import com.tornado.community.model.Notification;
import com.tornado.community.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class NotificationController {
    private final NotificationMapper notificationMapper;
    private final NotificationService notificationService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public NotificationController(NotificationMapper notificationMapper, NotificationService notificationService) {
        this.notificationMapper = notificationMapper;
        this.notificationService = notificationService;
    }

    @GetMapping("/notification/read")
    public String readNotification(@RequestParam("questionId") Integer questionId,
                                   @RequestParam("notificationId") Long notificationId,
                                   @RequestParam("receiverId") Integer receiverId,
                                   HttpSession session) {
        Notification notification = new Notification();
        notification.setId(notificationId);
        notification.setStatus(Constant.NotificationStatus.HAVE_READ);
        notificationMapper.updateByPrimaryKeySelective(notification);
        int unreadCount = notificationService.unreadCount(receiverId);
        session.setAttribute("unreadCount", unreadCount);
        return "redirect:/question/" + questionId;
    }
}
